package com.zlt.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CharSetFilter implements Filter {

    private String charset;

    /**
     * 当过滤器对象创建以后，会被调用一次
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharSetFilter创建");
        charset = filterConfig.getInitParameter("charset");
    }

    /**
     * 被拦截下来的请求，执行过滤的方法
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String method = req.getMethod();
        if("POST".equalsIgnoreCase(method)){
            req.setCharacterEncoding("utf-8");
        } else if("GET".equalsIgnoreCase(method)){
//            req = new MyRequest(req);
        }
        resp.setContentType("application/json;charset=utf-8");
        //放行  这个方法被调用，请求才可以到达目标资源  如果没有调用则请求被拦截访问不到目标资源
        chain.doFilter(req, resp);
    }

    /**
     * 过滤器对象被销毁之前会被调用一次
     */
    @Override
    public void destroy() {
        System.out.println("CharSetFilter过滤器销毁");
    }


}
